﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using SPContentDatabaseManager.Layouts;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;

namespace SPContentDatabaseManager.Layouts.SPContentDatabaseManager
{
    public partial class ViewSPSites : LayoutsPageBase
    {
        /* 
         *********************************************************************
         * Copyright 2014, Ryan Dennis
         * ryan@sharepointryan.com
         * www.sharepointryan.com
         * @SharePointRyan on Twitter
         * Ryan works for Blue Chip Consulting Group, www.bluechip-llc.com
         * All code is provided with no warranty or guarantees.
         * Visit the codeplex site: https://spcontentdbmanager.codeplex.com
         * Feel free to modify this code, but please leave this section 
         * in to give the original author credit.
         *********************************************************************
         */
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                siteGrid.AllowPaging = true;
                siteGrid.PageSize = 30;
                siteGrid.AllowSorting = true;
                ViewState["SortExpression"] = "Title";
                //BindGridView();
            }
        }
        private DataView BindGridView()
        {
            siteGrid.DataSource = null;
            siteGrid.DataBind();
            String guidStr = DatabasesForWebApp.SelectedValue.ToString();
            Guid dbGuid = new Guid(guidStr);
            SPContentDatabase selectedDb = SelectedWebApplication.CurrentItem.ContentDatabases[dbGuid];
            DataTable dt = new DataTable();
            DataRow dr;
            dt.Columns.Add(new DataColumn("Url", typeof(string)));
            dt.Columns.Add(new DataColumn("Title", typeof(string)));
            dt.Columns.Add(new DataColumn("Usage", typeof(string)));
            dt.Columns.Add(new DataColumn("MoveSite", typeof(string)));
            dt.Columns.Add(new DataColumn("SiteId", typeof(string)));
            dt.Columns.Add(new DataColumn("UsageInt", typeof(ulong)));
            for (int i = 0; i < selectedDb.Sites.Count; i++)
            {
                SPSite curSite = selectedDb.Sites[i];
                dr = dt.NewRow();
                dr[0] = curSite.Url.ToString();
                dr[1] = curSite.RootWeb.Title.ToString();
                dr[2] = Utilities.FormatBytes(curSite.Usage.Storage);
                dr[3] = "Move Site Collection";
                dr[4] = curSite.ID.ToString();
                dr[5] = Utilities.ConvertBytesToMegabytes(curSite.Usage.Storage);
                dt.Rows.Add(dr);
                curSite.Dispose();
            }
            ViewState["CurrentTable"] = dt;
            DataView dv = dt.DefaultView;
            dv.Sort = "Title ASC";

            siteGrid.DataSource = dt;
            siteGrid.PageSize = 30;
            siteGrid.DataBind();
            // Set tooltip and CSS classes for sortable link columns
            if (siteGrid.Rows.Count > 0)
            {
                siteGrid.HeaderRow.Cells[0].ToolTip = "Click to sort by Title";
                siteGrid.HeaderRow.Cells[1].ToolTip = "Click to sort by Site Url";
                siteGrid.HeaderRow.Cells[2].ToolTip = "Click to sort by Usage";
                // Return the dataview
                String cssclass = "spcdm-customHeaderAsc";
                siteGrid.HeaderRow.Cells[0].CssClass = cssclass;
                siteGrid.HeaderRow.Cells[0].ToolTip = "Click to sort by Title (Descending)";
            }
            return dv;
        }
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortDir = string.Empty;
            string notSortDir = string.Empty;
            String cssclass = string.Empty;
            if (direction == SortDirection.Ascending)
            {
                direction = SortDirection.Descending;
                sortDir = "Desc";
                notSortDir = "Ascending";
                cssclass = "spcdm-customHeaderDesc";
            }
            else
            {
                direction = SortDirection.Ascending;
                sortDir = "Asc";
                notSortDir = "Descending";
                cssclass = "spcdm-customHeaderAsc";
            }
            DataView sortedView = BindGridView();
            sortedView.Sort = e.SortExpression + " " + sortDir;
            Session["SortedView"] = sortedView;
            siteGrid.DataSource = sortedView;
            siteGrid.DataBind();
            siteGrid.HeaderRow.Cells[GetColumnIndex(e.SortExpression)].CssClass = cssclass;
            siteGrid.HeaderRow.Cells[0].ToolTip = "Click to sort by Title (" + notSortDir + ")";
            siteGrid.HeaderRow.Cells[1].ToolTip = "Click to sort by Site Url (" + notSortDir + ")";
            siteGrid.HeaderRow.Cells[2].ToolTip = "Click to sort by Usage (" + notSortDir + ")";
        }
        private string GetSortDirection(string column)
        {
            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string SortExpression = ViewState["SortExpression"] as string;

            if (SortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (SortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;
            return sortDirection;
        }
        protected void siteGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            siteGrid.PageIndex = e.NewPageIndex;
            if (Session["SortedView"] != null)
            {
                siteGrid.DataSource = Session["SortedView"];
                siteGrid.DataBind();
            }
            else
            {
                BindGridView();
            }
        }
        public SortDirection direction
        {
            get
            {
                if (ViewState["directionState"] == null)
                {
                    ViewState["directionState"] = SortDirection.Ascending;
                }
                return (SortDirection)ViewState["directionState"];
            }
            set
            {
                ViewState["directionState"] = value;
            }
        }
        protected void WebAppOnLoad(object sender, EventArgs e)
        {
            //Not currently doing anything fancy on web app load
        }
        protected void FillDatabaseSelector(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SPWebApplication webApp = SelectedWebApplication.CurrentItem;
                SPContentDatabaseCollection databases = webApp.ContentDatabases;
                Dictionary<string, string> dbList = new Dictionary<string, string>();
                for (int i = 0; i < databases.Count; i++)
                {
                    SPContentDatabase currentDb = databases[i];
                    dbList.Add(currentDb.Name, currentDb.Id.ToString());
                    DatabasesForWebApp.DataSource = dbList;
                    DatabasesForWebApp.DataTextField = "Key";
                    DatabasesForWebApp.DataValueField = "Value";
                    DatabasesForWebApp.DataBind();
                }
                DatabasesForWebApp.Items.Insert(0, "Select a database...");
            }
        }
        protected void OnDbChange(object sender, EventArgs e)
        {
            siteGrid.Visible = true;
            BindGridView();
        }
        private int GetColumnIndex(string SortExpression)
        {
            int i = 0;
            foreach (DataControlField c in siteGrid.Columns)
            {
                if (c.SortExpression == SortExpression)
                    break;
                i++;
            }
            return i;
        }
    }
}
